//
//  MXGamePopupView.swift
//  d11
//
//  Created by peale_pro on 2019/7/15.
//  Copyright © 2019年 Tech_001. All rights reserved.
//

import UIKit
import Lottie

typealias MXPopupViewPlatformSeltBlock = (_ dict: [String:Any],_ index:Int) -> Void
class MXGamePopupView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {
    var arrayList : [[String:Any]]? //数据列表
    var type : Int = 0
    var selectIndex = -1
    var selectDict : [String:Any]?
    var imgUrl :String?
    var typeName:String?
    var isHorizontalScreen :Bool = false
    var popScreenWidth : CGFloat = kScreenWidth
    var ipadAddHeight :CGFloat = 100
    var mXPopupViewPlatformSeltBlock: MXPopupViewPlatformSeltBlock?
    func callClickBlock(_ block: @escaping MXPopupViewPlatformSeltBlock) {
        mXPopupViewPlatformSeltBlock = block
    }
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
         layout.minimumInteritemSpacing = 0
        
        if arrayList?.count ?? 0  == 1{
            layout.itemSize = CGSize(width: self.popScreenWidth-50, height: 295+ipadAddHeight)
        }else if arrayList?.count ?? 0  == 2 {
            layout.itemSize = CGSize(width: self.popScreenWidth-50, height: (295+ipadAddHeight)/2)
        }else{
            layout.itemSize = CGSize(width: (self.popScreenWidth-55)/2, height: (295+ipadAddHeight)/4)
            layout.minimumInteritemSpacing = 5
        }
       
        layout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
       
        //  }
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        // layout.headerReferenceSize = CGSize.init(width: (kScreenWidth-20)/4, height: 87.5)
        // 设置分区头视图和尾视图宽高
        //    layout.headerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        //    layout.footerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        let itemHeight = (295+ipadAddHeight)/4
        var collViewWidht = self.popScreenWidth-40
        var collView = UICollectionView.init(frame: CGRect(x:0, y:45, width:collViewWidht, height:360+ipadAddHeight), collectionViewLayout: layout)
        if arrayList?.count ?? 0  >= 3{
            var count = (arrayList?.count ?? 0) / 2
            if (arrayList?.count ?? 0) % 2 != 0{
                count += 1
            }
            if count > 4 {
                count = 4
            }
            collView = UICollectionView.init(frame: CGRect(x:0, y:45, width:Int(collViewWidht), height:65+(count*Int(itemHeight))), collectionViewLayout: layout)
        }
       
        
        if collView.responds(to:#selector(setter: UIView.layoutMargins)) {
            collView.layoutMargins = .zero;
        }
        
        collView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth.union(UIView.AutoresizingMask.flexibleHeight)
        collView.register(MXGamePopupViewItemCell.self, forCellWithReuseIdentifier: "MXGamePopupViewItemCell")
        //        collView.register(HelperListHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HelperListHeadView1")
        collView.showsVerticalScrollIndicator = false
        collView.showsHorizontalScrollIndicator = false
        collView.delegate = self
        collView.dataSource = self
        collView.backgroundColor = UIColor.white
       // collView.layer.cornerRadius = 5;
        //collView.layer.masksToBounds = true
        // collView.backgroundColor = UIColor.red
        return collView
    }()
    
    convenience init(gameArray:[[String:Any]]?,imgUrl:String,typeName:String,isHorizontalScreen:Bool) {
        self.init(frame: UIScreen.main.bounds)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        self.backgroundColor = UIColor.clear
        window.addSubview(self)
        self.imgUrl = imgUrl
        self.typeName = typeName
        self.arrayList = []
        self.isHorizontalScreen = isHorizontalScreen
        if gameArray != nil{
            self.arrayList = gameArray
        }
        self.popScreenWidth = kScreenWidth
        if kIsIpad == true{
            if kScreenWidth < 415+100{
                self.popScreenWidth = kScreenWidth
                self.ipadAddHeight = kScreenWidth-415
            }else{
                self.popScreenWidth = 415+100
            }
           
        }else{
              self.ipadAddHeight = 0
        }
        //感知设备方向 - 开启监听设备方向
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        //添加通知，监听设备方向改变
        NotificationCenter.default.addObserver(self, selector: #selector(MXGamePopupView.receivedRotation), name: UIDevice.orientationDidChangeNotification, object: nil)
       self.initUI()
    }
    
    @objc func receivedRotation(){
        self.closePageView()
    }
    
    @objc func closePageView() -> Void {
        self.removeFromSuperview()
    }
    func initUI(){
        //360
        let bgView :UIView  = UIView.init()
         bgView.backgroundColor = RGBAlpa(0,0,0,0.4)
        bgView.tag = 2001
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        ////        let effecView = UIHelper.showBlurEffect(isClick:true)
        ////       window.addSubview(effecView)
        self.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        let whiteView = UIView.init()
        whiteView.backgroundColor = HexRGBAlpha(0xf6f8fa, 1)
        whiteView.layer.cornerRadius = 5;
        whiteView.layer.masksToBounds = true
        self.addSubview(whiteView)
        whiteView.snp.makeConstraints { (make) in
            if kIsIpad == true{
                make.width.equalTo(self.popScreenWidth-20)
            }else{
                if self.isHorizontalScreen == true{
                    make.width.equalTo(self.snp.height).offset(-20)
                }else{
                    make.width.equalToSuperview().offset(-20)
                }
                
            }
            if kScreenWidth <= 320 && self.isHorizontalScreen == true {
                make.height.equalTo(300)
            }else{
                let itemHeight = (295+ipadAddHeight)/4
                if arrayList?.count ?? 0  >= 3{
                    var count = (arrayList?.count ?? 0) / 2
                    if (arrayList?.count ?? 0) % 2 != 0{
                        count += 1
                    }
                    if count > 4 {
                        count = 4
                    }
                    make.height.equalTo((65 + count * Int(itemHeight)))
                }else{
                    make.height.equalTo(360+ipadAddHeight)
                }
            }
            
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
//        let iconAnimationView = AnimationView.init(contentsOf: URL(string: imgUrl ?? "")!)
        let iconAnimationView = AnimationView.init(url: URL(string: imgUrl ?? "")!, closure: {
            down in
        })

     
        whiteView.addSubview(iconAnimationView)
       iconAnimationView.snp.makeConstraints{(make) in
            make.width.equalTo(25)
            make.height.equalTo(25)
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(20)
        }
       iconAnimationView.play(completion: { (animationFinished) in
            
        })
        let closeLabel = UILabel.init()
        closeLabel.textColor = HexRGBAlpha(0x747474, 1)
        closeLabel.font = UIFont.systemFont(ofSize: 20)
        closeLabel.text =  "X"
        closeLabel.textAlignment = .right
        closeLabel.isUserInteractionEnabled = true
        closeLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        whiteView.addSubview(closeLabel)
        closeLabel.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(25)
            make.width.equalTo(40)
            make.top.equalToSuperview().offset(10)
        }
        let nameLabel = UILabel.init()
        nameLabel.textColor = HexRGBAlpha(0x747474, 1)
        nameLabel.font = UIFont.systemFont(ofSize: 15)
        nameLabel.text =  self.typeName
        nameLabel.textAlignment = .left
        whiteView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints{(make) in
            make.left.equalTo(iconAnimationView.snp.right).offset(15)
            make.right.equalTo(closeLabel.snp.left).offset(15)
            make.height.equalTo(25)
            make.top.equalToSuperview().offset(10)
        }
        
        whiteView.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrayList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        return UICollectionReusableView.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MXGamePopupViewItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MXGamePopupViewItemCell", for: indexPath) as! MXGamePopupViewItemCell
        let dict:[String:Any] = self.arrayList?[indexPath.row] ?? [:]
        cell.setData(imgUrl: dict["imgNameIOS_Ipad"] as? String ?? "",gameId:dict["id"] as? String ?? "",gameCount: arrayList?.count ?? 0)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectIndex = indexPath.row
        if mXPopupViewPlatformSeltBlock != nil {
            mXPopupViewPlatformSeltBlock!(self.arrayList?[self.selectIndex] ?? [:],self.selectIndex)
        }
        self.collectionView.reloadData()
        self.closePageView()
//        let skipTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.timerTick), userInfo: nil, repeats: false)
//        RunLoop.main.add(skipTimer, forMode: RunLoop.Mode.common)
        
    }
}
